<?php

require_once(DIR_FS_CATALOG . DIR_WS_CLASSES . "way2ship.php");

define(W2S_HIDDEN_SERVICE_START_TAG, 'span id="w2s_');
define(W2S_HIDDEN_SERVICE_END_TAG, '"/>');
define(W2S_MODULE_VERSION, "1.4.4");

 
new Way2ShipInstaller();

function way2ship_install_getServiceByCarrier($carrier_code) {
	$settings = new Way2ShipSettings();
	$w2s_carrier_services = $settings->getServicesByCarrier($carrier_code);
	$retVal = array_values($w2s_carrier_services);
	array_unshift($retVal, "None");
	return $retVal;
}

class Way2ShipOSC {
	var $w2sOSC_carriers = array(
		W2S_FEDEX_CARRIER => MODULE_SHIPPING_WAY2SHIP_FEDEX_SERVICE_NAME,
		W2S_PUROLATOR_CARRIER => MODULE_SHIPPING_WAY2SHIP_PUROLATOR_SERVICE_NAME,
		W2S_DHL_CARRIER => MODULE_SHIPPING_WAY2SHIP_DHL_SERVICE_NAME,
		W2S_CANADA_POST_CARRIER => MODULE_SHIPPING_WAY2SHIP_CANADA_POST_SERVICE_NAME,
		W2S_UPS_CARRIER => MODULE_SHIPPING_WAY2SHIP_UPS_SERVICE_NAME);
		
	var $w2sOSC_services = array(
	    W2S_FEDEX_CARRIER => array(
	    1 => MODULE_SHIPPING_WAY2SHIP_FEDEX_PRIORITY_SERVICE, 
	    2 => MODULE_SHIPPING_WAY2SHIP_FEDEX_OVERNIGHT_SERVICE, 
	    3 => MODULE_SHIPPING_WAY2SHIP_FEDEX_GROUND_SERVICE, 
	  	28 => MODULE_SHIPPING_WAY2SHIP_FEDEX_STANDARD_OVERNIGHT_SERVICE, 
	  	29 => MODULE_SHIPPING_WAY2SHIP_FEDEX_SECOND_DAY_SERVICE),
	  	 
	    W2S_PUROLATOR_CARRIER => array(
	    4 => MODULE_SHIPPING_WAY2SHIP_PUROLATOR_AIR, 
	    5 => MODULE_SHIPPING_WAY2SHIP_PUROLATOR_AIR_9AM, 
	    6 => MODULE_SHIPPING_WAY2SHIP_PUROLATOR_AIR_1030,
	  	7 => MODULE_SHIPPING_WAY2SHIP_PUROLATOR_PUROLETTER, 
	  	8 => MODULE_SHIPPING_WAY2SHIP_PUROLATOR_PUROLETTER_9AM, 
	  	9 => MODULE_SHIPPING_WAY2SHIP_PUROLATOR_PUROLETTER_1030, 
	  	10 => MODULE_SHIPPING_WAY2SHIP_PUROLATOR_PUROPAK, 
	  	11 => MODULE_SHIPPING_WAY2SHIP_PUROLATOR_PUROPAK_9AM, 
	  	12 => MODULE_SHIPPING_WAY2SHIP_PUROLATOR_PUROPAK_1030, 
	  	13 => MODULE_SHIPPING_WAY2SHIP_PUROLATOR_GROUND, 
	  	19 => MODULE_SHIPPING_WAY2SHIP_PUROLATOR_GROUND_9AM, 
	  	20 => MODULE_SHIPPING_WAY2SHIP_PUROLATOR_GROUND_1030),
	    
	  	W2S_DHL_CARRIER => array(
	  	100 => MODULE_SHIPPING_WAY2SHIP_DHL_EXPRESS, 
	  	101 => MODULE_SHIPPING_WAY2SHIP_DHL_EXPRESS_1030, 
	  	102 => MODULE_SHIPPING_WAY2SHIP_DHL_EXPRESS_SATURDAY,
	  	103 => MODULE_SHIPPING_WAY2SHIP_DHL_EXPRESS_SECOND_DAY, 
	  	104 => MODULE_SHIPPING_WAY2SHIP_DHL_NEXT_AFTERNOON, 
	  	105 => MODULE_SHIPPING_WAY2SHIP_DHL_GROUND, 
	  	106 => MODULE_SHIPPING_WAY2SHIP_DHL_INTERNATIONAL_EXPRESS), 
	    
	  	W2S_CANADA_POST_CARRIER => array (
	  	500 => MODULE_SHIPPING_WAY2SHIP_CANADA_POST_PRIORITY, 
	  	501 => MODULE_SHIPPING_WAY2SHIP_CANADA_POST_XPRESS_POST, 
	  	502 => MODULE_SHIPPING_WAY2SHIP_CANADA_POST_EXPEDITED,
	  	503 => MODULE_SHIPPING_WAY2SHIP_CANADA_POST_REGULAR, 
	  	504 => MODULE_SHIPPING_WAY2SHIP_CANADA_POST_XPRESS_USA, 
	  	505 => MODULE_SHIPPING_WAY2SHIP_CANADA_POST_XPRESS_INTL, 
	  	506 => MODULE_SHIPPING_WAY2SHIP_CANADA_POST_AIR_PARCEL_INTL,
	  	507 => MODULE_SHIPPING_WAY2SHIP_CANADA_POST_SURFACE_PARCEL_INTL, 
	  	508 => MODULE_SHIPPING_WAY2SHIP_CANADA_POST_EXPEDITED_PARCEL_USA), 
	    
	  	W2S_UPS_CARRIER => array(
	  	600 => MODULE_SHIPPING_WAY2SHIP_UPS_EXPRESS, 
	  	601 => MODULE_SHIPPING_WAY2SHIP_UPS_EXPEDITED, 
	  	602 => MODULE_SHIPPING_WAY2SHIP_UPS_WORLDWIDE_EXPRESS, 
	  	603 => MODULE_SHIPPING_WAY2SHIP_UPS_WORLDWIDE_EXPEDITED, 
	  	604 => MODULE_SHIPPING_WAY2SHIP_UPS_STANDARD, 
	  	605 => MODULE_SHIPPING_WAY2SHIP_UPS_EXPRESS_EARLY_AM, 
	  	606 => MODULE_SHIPPING_WAY2SHIP_UPS_EXPRESS_3DAY_SELECT, 
	  	607 => MODULE_SHIPPING_WAY2SHIP_UPS_SAVER,
	  	608 => MODULE_SHIPPING_WAY2SHIP_UPS_GROUND,
	  	609 => MODULE_SHIPPING_WAY2SHIP_UPS_NEXT_DAY_SAVER,
	  	610 => MODULE_SHIPPING_WAY2SHIP_UPS_WORLDWIDE_EXPRESS_PLUS,
	  	611 => MODULE_SHIPPING_WAY2SHIP_UPS_SECOND_DAY_AM),

	  	W2S_CANADA_POST_DIRECT_CARRIER => array (
	  	1010 => MODULE_SHIPPING_WAY2SHIP_CANADAPOST_DIRECT_REGULAR, 
	  	1020 => MODULE_SHIPPING_WAY2SHIP_CANADAPOST_DIRECT_EXPEDITED,
	  	1030 => MODULE_SHIPPING_WAY2SHIP_CANADAPOST_DIRECT_XPRESSPOST, 
	  	1040 => MODULE_SHIPPING_WAY2SHIP_CANADAPOST_DIRECT_PRIORITY,
	  	2005 => MODULE_SHIPPING_WAY2SHIP_CANADAPOST_DIRECT_SMALL_PACKETS_SURFACE_USA,
	  	2015 => MODULE_SHIPPING_WAY2SHIP_CANADAPOST_DIRECT_SMALL_PACKETS_AIR_USA,
		2020 => MODULE_SHIPPING_WAY2SHIP_CANADAPOST_DIRECT_EXPEDITED_PARCEL_USA,
		2025 => MODULE_SHIPPING_WAY2SHIP_CANADAPOST_DIRECT_EXPEDITED_USA,
	  	2030 => MODULE_SHIPPING_WAY2SHIP_CANADAPOST_DIRECT_XPRESSPOST_USA,	  	
	  	2040 => MODULE_SHIPPING_WAY2SHIP_CANADAPOST_DIRECT_PRIORITY_PARCEL_USA,
	  	2050 => MODULE_SHIPPING_WAY2SHIP_CANADAPOST_DIRECT_PRIORITY_PACK_USA,	  		  	
	  	3005 => MODULE_SHIPPING_WAY2SHIP_CANADAPOST_DIRECT_SMALL_PACKETS_SURFACE_INT,
	  	3010 => MODULE_SHIPPING_WAY2SHIP_CANADAPOST_DIRECT_SMALL_PARCEL_SURFACE_INT,
	  	3015 => MODULE_SHIPPING_WAY2SHIP_CANADAPOST_DIRECT_SMALL_PACKETS_AIR_INT,
	  	3020 => MODULE_SHIPPING_WAY2SHIP_CANADAPOST_DIRECT_SMALL_PARCEL_AIR_INT,
	  	3025 => MODULE_SHIPPING_WAY2SHIP_CANADAPOST_DIRECT_XPRESSPOST_INT,	  	
	  	3040 => MODULE_SHIPPING_WAY2SHIP_CANADAPOST_DIRECT_PRIORITY_PARCEL_INT,
	  	3050 => MODULE_SHIPPING_WAY2SHIP_CANADAPOST_DIRECT_PRIORITY_PACK_INT),
	  	 
	    W2S_FEDEX_DIRECT_CARRIER => array(
	    5000 => MODULE_SHIPPING_WAY2SHIP_FEDEX_DIRECT_FIRST_OVERNIGHT,
	    5001 => MODULE_SHIPPING_WAY2SHIP_FEDEX_DIRECT_PRIORITY_OVERNIGHT,
	    5002 => MODULE_SHIPPING_WAY2SHIP_FEDEX_DIRECT_STANDARD_OVERNIGHT,
	    5003 => MODULE_SHIPPING_WAY2SHIP_FEDEX_DIRECT_SECOND_DAY,
	    5004 => MODULE_SHIPPING_WAY2SHIP_FEDEX_DIRECT_EXPRESS_SAVER,
	    5005 => MODULE_SHIPPING_WAY2SHIP_FEDEX_DIRECT_GROUND,
	    5006 => MODULE_SHIPPING_WAY2SHIP_FEDEX_DIRECT_GROUND_HOME,
	    5007 => MODULE_SHIPPING_WAY2SHIP_FEDEX_DIRECT_INT_FIRST,	    
	    5008 => MODULE_SHIPPING_WAY2SHIP_FEDEX_DIRECT_INT_PRIORITY,	    
	    5009 => MODULE_SHIPPING_WAY2SHIP_FEDEX_DIRECT_INT_ECONOMY,	    
	    5010 => MODULE_SHIPPING_WAY2SHIP_FEDEX_DIRECT_EUROPE_PRIORITY),
	    
	  	W2S_UPS_DIRECT_CARRIER_US => array(
	  	7001 => MODULE_SHIPPING_WAY2SHIP_UPS_DIRECT_US_NEXT_DAY_AIR, 
	  	7002 => MODULE_SHIPPING_WAY2SHIP_UPS_DIRECT_US_SECOND_DAY_AIR, 
	  	7003 => MODULE_SHIPPING_WAY2SHIP_UPS_DIRECT_US_GROUND, 
	  	7004 => MODULE_SHIPPING_WAY2SHIP_UPS_DIRECT_US_3DAY, 
	  	7005 => MODULE_SHIPPING_WAY2SHIP_UPS_DIRECT_US_NEXT_AIR_SAVER, 
	  	7006 => MODULE_SHIPPING_WAY2SHIP_UPS_DIRECT_US_NEXT_EARLY, 
	  	7007 => MODULE_SHIPPING_WAY2SHIP_UPS_DIRECT_US_SECOND_AM, 
	  	7008 => MODULE_SHIPPING_WAY2SHIP_UPS_DIRECT_US_SAVER,
		7009 => MODULE_SHIPPING_WAY2SHIP_UPS_DIRECT_US_STANDARD, 
	  	7010 => MODULE_SHIPPING_WAY2SHIP_UPS_DIRECT_US_WW_EXPRESS, 
	  	7011 => MODULE_SHIPPING_WAY2SHIP_UPS_DIRECT_US_WW_EXPEDITED, 
	  	7012 => MODULE_SHIPPING_WAY2SHIP_UPS_DIRECT_US_WW_EXPRESS_PLUS),	    

	  	W2S_UPS_DIRECT_CARRIER_CA => array(
	  	7050 => MODULE_SHIPPING_WAY2SHIP_UPS_DIRECT_CA_EXPRESS, 
	  	7051 => MODULE_SHIPPING_WAY2SHIP_UPS_DIRECT_CA_EXPEDITED, 
	  	7052 => MODULE_SHIPPING_WAY2SHIP_UPS_DIRECT_CA_WW_EXPRESS, 
	  	7053 => MODULE_SHIPPING_WAY2SHIP_UPS_DIRECT_CA_WW_EXPEDITED, 
	  	7054 => MODULE_SHIPPING_WAY2SHIP_UPS_DIRECT_CA_STANDARD, 
	  	7055 => MODULE_SHIPPING_WAY2SHIP_UPS_DIRECT_CA_3DAY_SELECT, 
	  	7056 => MODULE_SHIPPING_WAY2SHIP_UPS_DIRECT_CA_SAVER, 
	  	7057 => MODULE_SHIPPING_WAY2SHIP_UPS_DIRECT_CA_EXPRESS_EARLY_AM,
		7058 => MODULE_SHIPPING_WAY2SHIP_UPS_DIRECT_CA_WW_EXPRESS_PLUS, 
	  	7059 => MODULE_SHIPPING_WAY2SHIP_UPS_DIRECT_CA_SAVER1),	    	  		
	    
	  	W2S_UPS_DIRECT_CARRIER_INT => array(
	  	7100 => MODULE_SHIPPING_WAY2SHIP_UPS_DIRECT_INT_EXPRESS, 
	  	7101 => MODULE_SHIPPING_WAY2SHIP_UPS_DIRECT_INT_EXPEDITED, 
	  	7102 => MODULE_SHIPPING_WAY2SHIP_UPS_DIRECT_INT_STANDARD, 
		7103 => MODULE_SHIPPING_WAY2SHIP_UPS_DIRECT_INT_WW_EXPRESS_PLUS, 
	  	7104 => MODULE_SHIPPING_WAY2SHIP_UPS_DIRECT_INT_SAVER)	    	  	
	    );		    
	    
	function quote($order, $cart, $requestedCarrier, $requestedServices, $forcedHandling, 
		$fallbackService, $fallBackCost) {
			
		global $order;

		$w2s = new Way2Ship(SHIPPING_WAY2SHIP_USERNAME, SHIPPING_WAY2SHIP_PASSWORD);

		// get the country code
		$country_array = tep_get_countries(SHIPPING_WAY2SHIP_ORIGIN_COUNTRY, true);
		// prepare origin address
		$originAddress = new W2SQuoteLocation(SHIPPING_WAY2SHIP_ORIGIN_ZIP, SHIPPING_WAY2SHIP_ORIGIN_STATE,
		$country_array['countries_iso_code_2']);
			
		// get destination state/province code
		$dest_state_code = tep_get_zone_code($order->delivery['country']['id'], $order->delivery['zone_id'], '');
		// prepare destination address
		$destinationAddress = new W2SQuoteLocation($order->delivery['postcode'], $dest_state_code,
		$order->delivery['country']['iso_code_2'], $order->delivery['street_address'], $order->delivery['suburb'],
		$order->delivery['city']);
		
		$quoteRequest = new W2SQuoteOrder($originAddress, $destinationAddress, $cart->show_total());

		// now add the cart content
		$productsArray = $cart->get_products();
		foreach ($productsArray as $product) {
			$quoteRequest->addOrderItem($this->createItem($product['id'], $product['weight'], 
				$product['final_price'], $product['quantity'], $product['model']));
		}
		
		$quoteRequest->cart_url = HTTP_SERVER . DIR_WS_HTTP_CATALOG;

		$quotesCont = $w2s->getQuotes($quoteRequest, $requestedCarrier, $requestedServices);
		
		$quoteLines = array();
		
		//handling fee
		$handlingFee = SHIPPING_WAY2SHIP_HANDLING_FEE;
		if (is_numeric($forcedHandling)) {
			$handlingFee = $forcedHandling;	 
		}
	
		if ($quotesCont->isError) {
			if ((is_numeric($fallbackService) && is_numeric($fallBackCost)) &&
				// validation errors should be passed through
				stristr($quotesCont->errorMessage, 'is missing') === FALSE &&
				stristr($quotesCont->errorMessage, 'is invalid') === FALSE &&
				stristr($quotesCont->errorMessage, 'does not match') === FALSE &&
				stristr($quotesCont->errorMessage, 'Could not authenticate user') === FALSE) {				
			
				$title = $this->w2sOSC_carriers[$requestedCarrier] . ' ' . $this->w2sOSC_services[$requestedCarrier][$fallbackService];
				$title.= '<' . W2S_HIDDEN_SERVICE_START_TAG . $fallbackService . W2S_HIDDEN_SERVICE_END_TAG;
				$quoteLines[] = array('id' => $fallbackService, 'title' => $title, 'cost' => ($fallBackCost + $handlingFee));
				return $quoteLines;
			} else {
				return $quotesCont->errorMessage;
			}
		}
		$quotes = $quotesCont->quotes;
		
		for ($i=0; $i < count($quotes); $i++) {
			$quote = $quotes[$i];
			$title = $this->w2sOSC_carriers[$quote->carrierId] . ' ' . $this->w2sOSC_services[$quote->carrierId][$quote->serviceId];
			if ($quote->transitDays > 0) {
				$date = strtotime($quote->estimatedDeliveryDate);
				$eta_part = sprintf(MODULE_SHIPPING_WAY2SHIP_ETA_LINE, strftime("%a, %b %d", $date)); 
				$title = sprintf($title, $eta_part, strftime("%a, %b %d", $date), $quote->transitDays); 				 
			} else {
				$title = sprintf($title, '', '', '');
			}
			$title.= '<' . W2S_HIDDEN_SERVICE_START_TAG . $quote->serviceId . W2S_HIDDEN_SERVICE_END_TAG;
			$quoteLines[] = array('id' => $quote->serviceId, 'title' => $title, 'cost' => ($quote->totalCharge + $handlingFee));
		}
		return $quoteLines;
	}
	
	function createItem($productID, $weight, $price, $quantity, $model) {
		$item = new W2SQuoteOrderItem($weight, $price, $quantity, $model);
			
		if (SHIPPING_WAY2SHIP_WEIGHT_UNITS == 'kg') {
			$item->setWeightMetricUnits();
		} else {
			$item->setWeightImperialUnits();
		}

		if (SHIPPING_WAY2SHIP_DIM_UNITS == 'cm') {
			$item->setDimMetricUnits();
		} else {
			$item->setDimImperialUnits();
		}
			
		// get units and optional dimensions
		if (SHIPPING_WAY2SHIP_DIM_LENGTH_FIELD != '' &&
		SHIPPING_WAY2SHIP_DIM_WIDTH_FIELD != '' &&
		SHIPPING_WAY2SHIP_DIM_HEIGHT_FIELD != '') {
			// use dimensions
			$product_dim_query = tep_db_query("select " . SHIPPING_WAY2SHIP_DIM_LENGTH_FIELD .
					", " . SHIPPING_WAY2SHIP_DIM_WIDTH_FIELD .
					", " . SHIPPING_WAY2SHIP_DIM_HEIGHT_FIELD . 
					" from " . TABLE_PRODUCTS . " where products_id = '" . $productID . "'");

			if ($product_dim = tep_db_fetch_array($product_dim_query)) {
				$item->length = $product_dim[SHIPPING_WAY2SHIP_DIM_LENGTH_FIELD];
				$item->width =  $product_dim[SHIPPING_WAY2SHIP_DIM_WIDTH_FIELD];
				$item->height =  $product_dim[SHIPPING_WAY2SHIP_DIM_HEIGHT_FIELD];
			}
		}
		
		return $item;
		 
	}

	function buildShipXML() {
		$w2s = new Way2Ship(SHIPPING_WAY2SHIP_USERNAME, SHIPPING_WAY2SHIP_PASSWORD);
		 
		$ordersToShip;
		 
		$sql = "select o.orders_id,  tot.title, tot.value, co.countries_id, co.countries_iso_code_2, zo.zone_code from orders_total tot, orders o " .
    	" left outer join countries co on o.delivery_country = co.countries_name " .
    	" left outer join zones zo on (zo.zone_country_id = co.countries_id and zo.zone_name = o.delivery_state) " .
    	" where o.orders_id = tot.orders_id and tot.class = 'ot_shipping' " . 
    	" and o.orders_status = " . SHIPPING_WAY2SHIP_ORDER_STATUS_TOSHIP . " and tot.title LIKE '%" . W2S_HIDDEN_SERVICE_START_TAG . "%'";

		$orders_query = tep_db_query($sql);
		 
		while ($orders = tep_db_fetch_array($orders_query)) {
			$oID = $orders['orders_id'];
			$cartOrder = new order($oID);
			$shipping_line = $orders['title'];


			$startTagPos = strpos($shipping_line, W2S_HIDDEN_SERVICE_START_TAG);
			$endTagPos = strpos($shipping_line, W2S_HIDDEN_SERVICE_END_TAG);
			$length = $endTagPos - ($startTagPos + strlen(W2S_HIDDEN_SERVICE_START_TAG));
			$serviceID = substr($shipping_line, $startTagPos + strlen(W2S_HIDDEN_SERVICE_START_TAG), $length);

			// get the country code
			$country_array = tep_get_countries(SHIPPING_WAY2SHIP_ORIGIN_COUNTRY, true);
			$fromLocation = new W2SShipLocation(SHIPPING_WAY2SHIP_ORIGIN_ZIP, SHIPPING_WAY2SHIP_ORIGIN_STATE,
			$country_array['countries_iso_code_2'],
			SHIPPING_WAY2SHIP_ORIGIN_ADDRESS, SHIPPING_WAY2SHIP_ORIGIN_ADDRESS2, SHIPPING_WAY2SHIP_ORIGIN_CITY);
				
			$fromContact = new W2SShipContact(STORE_NAME, SHIPPING_WAY2SHIP_SHIPPING_CONTACT,
			SHIPPING_WAY2SHIP_SHIPPING_CONTACT_PHONE, SHIPPING_WAY2SHIP_SHIPPING_CONTACT_EMAIL);
				
				
			$toLocation = new W2SShipLocation($cartOrder->delivery['postcode'],
			$orders['zone_code'],
			$orders['countries_iso_code_2'],
			$cartOrder->delivery['street_address'],
			$cartOrder->delivery['suburb'],
			$cartOrder->delivery['city']
);

			$toContact = new W2SShipContact($cartOrder->delivery['company'],
			$cartOrder->delivery['name'],
			$cartOrder->customer['telephone'],
			$cartOrder->customer['email_address']);
			 

			$orderToShip = new W2SShipOrder($oID, $fromLocation, $fromContact, $toLocation, $toContact, $serviceID);

			//get the totals
			$totals_query = tep_db_query("select class, value from orders_total where orders_id = " . $oID);
			 
			while ($totals = tep_db_fetch_array($totals_query)) {
				$type = $totals['class'];
				if ($type == 'ot_subtotal') {
					$orderToShip->subTotal = round($totals['value'], 2);
				} elseif ($type == 'ot_shipping') {
					$orderToShip->shippingCharge = round($totals['value'], 2);
				} elseif ($type == 'ot_total') {
					$orderToShip->total = round($totals['value'], 2);
				}
			}

			// now add the products
			$productsArray = $cartOrder->products;
			foreach ($productsArray as $product) {
				// get product's weight
				$weight_query = tep_db_query("select products_weight from " . TABLE_PRODUCTS . 
					" where products_id = '" . $product['id'] . "'");
				if (tep_db_num_rows($weight_query)) {
		  			$weightRow = tep_db_fetch_array($weight_query);
		  			$weight = $weightRow['products_weight'];
				}
				
				$orderToShip->addOrderItem($this->createItem($product['id'], $weight, $product['final_price'], 
					$product['qty'], $product['model']));
			}
			
			$ordersToShip[] = $orderToShip;
		}
		 
		return $w2s->buildOrdersXML($ordersToShip);
	}
	
	function updateOrders($updateXML) {
		$w2s = new Way2Ship(SHIPPING_WAY2SHIP_USERNAME, SHIPPING_WAY2SHIP_PASSWORD);
		$ordersUpdates = $w2s->getOrdersUpdates($updateXML);
		
		foreach($ordersUpdates as $orderUpdate) {
			// now update the order status and the order history
		    $oID = $orderUpdate->orderID;
		    
		    // process only label generated statuses
		    if ($orderUpdate->orderStatus != W2S_ORDER_STATUS_LABEL_GENERATED) continue;
        	
		    $status = SHIPPING_WAY2SHIP_ORDER_STATUS_TOUPDATE;
        	
		    $check_status_query = tep_db_query("select customers_name, customers_email_address, orders_status, date_purchased from " . TABLE_ORDERS . " where orders_id = '" . (int)$oID . "'");
			if (!tep_db_num_rows($check_status_query)) {
		    	//the order is gone
		    	continue;
		    }		    
        	$check_status = tep_db_fetch_array($check_status_query);        	
	        
	
	        tep_db_query("update " . TABLE_ORDERS . " set orders_status = '" . tep_db_input($status) . "', last_modified = now() where orders_id = '" . (int)$oID . "'");	
	        
	        $notify_comments = sprintf(EMAIL_TEXT, $orderUpdate->trackingNumber, $orderUpdate->trackingURL) . "\n\n";
	        $status_comment = sprintf(TEXT_STATUS_CHANGE_COMMENT, $orderUpdate->trackingNumber);
	        
	        if (SHIPPING_WAY2SHIP_NOTIFY_CUSTOMER_ON_SHIPPING) {
		        $email = STORE_NAME . "\n" . EMAIL_SEPARATOR . "\n" . EMAIL_TEXT_ORDER_NUMBER . ' ' . $oID . "\n" . 
		        	EMAIL_TEXT_DATE_ORDERED . ' ' . tep_date_long($check_status['date_purchased']) . "\n\n" .
		        	$notify_comments; 	        		
		        		        	
		        tep_mail($check_status['customers_name'], $check_status['customers_email_address'], sprintf(EMAIL_TEXT_SUBJECT, $oID), $email, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS);
	        }
	        // update the status history
	        tep_db_query("insert into " . TABLE_ORDERS_STATUS_HISTORY . " (orders_id, orders_status_id, date_added, customer_notified, comments) values ('" . (int)$oID . "', '" . tep_db_input($status) . "', now(), '" . tep_db_input(1) . "', '" . tep_db_input($status_comment)  . "')");	        			
		}
		
		return "OK";
	}
}

class Way2ShipInstaller {
	/**
	 * Adds configuration settings if they are missing
	 *
	 * @return Way2ShipInstaller
	 */
	function Way2ShipInstaller() {

		
		// Create a group for WayToShip configuration		
		// check if the group exists
		$group_query = tep_db_query("SELECT configuration_group_id FROM " . TABLE_CONFIGURATION_GROUP . " where configuration_group_id = 50");
		if (tep_db_num_rows($group_query) < 1)  { 
			tep_db_query("insert into " . TABLE_CONFIGURATION_GROUP . " (configuration_group_id, configuration_group_title, configuration_group_description, sort_order, visible) values ('50', 'WayToShip', 'Configuration for WayToShip shipping modules. Please make sure to fill in all mandatory fields marked with a * sign.', '50', '1')");	
		}		
		
		if (defined('SHIPPING_ORIGIN_STATE')) { 
			// upgrade from version 1.3 or lower
			
			// Move all the existing configuration under WayToShip group 
			tep_db_query("UPDATE "  . TABLE_CONFIGURATION .  " SET configuration_group_id='50' WHERE configuration_key LIKE 'SHIPPING_WAY2SHIP%'");
			
			// Create new state, country and zip entries amd move the information from the existing ones
			if (!defined('SHIPPING_WAY2SHIP_ORIGIN_STATE')) {
				tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('*Origin state', 'SHIPPING_WAY2SHIP_ORIGIN_STATE', '" . SHIPPING_ORIGIN_STATE . "', 'Enter two letter state/province you are shipping from.', '50', '23', now())");
				define('SHIPPING_WAY2SHIP_ORIGIN_STATE', SHIPPING_ORIGIN_STATE);
				// remove the old entry
				tep_db_query("delete from "  . TABLE_CONFIGURATION . " where configuration_key = 'SHIPPING_ORIGIN_STATE'");
			}
	
			if (!defined('SHIPPING_WAY2SHIP_ORIGIN_ZIP')) {
				tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('*Origin zip/postal code', 'SHIPPING_WAY2SHIP_ORIGIN_ZIP', '" . SHIPPING_ORIGIN_ZIP . "', 'Enter ZIP/Postal code are shipping from.', '50', '24', now())");
				define('SHIPPING_WAY2SHIP_ORIGIN_ZIP', SHIPPING_ORIGIN_ZIP);
			}
					
			if (!defined('SHIPPING_WAY2SHIP_ORIGIN_COUNTRY')) {
				tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, use_function, date_added) values ('*Origin country', 'SHIPPING_WAY2SHIP_ORIGIN_COUNTRY', '" . SHIPPING_ORIGIN_COUNTRY . "', 'Select the country you are shipping from.', '50', '25', 'tep_cfg_pull_down_country_list(', 'tep_get_country_name', now())");
				define('SHIPPING_WAY2SHIP_ORIGIN_COUNTRY', SHIPPING_ORIGIN_COUNTRY);
			}					
		}
		
		
		// USername and password
		if (!defined('SHIPPING_WAY2SHIP_USERNAME')) {
			tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('*WayToShip username', 'SHIPPING_WAY2SHIP_USERNAME', 'demo', 'Enter your WayToShip username.', '50', '10', now())");
		}
		if (!defined('SHIPPING_WAY2SHIP_PASSWORD')) {
			tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('*WayToShip password', 'SHIPPING_WAY2SHIP_PASSWORD', 'demo', 'Enter your WayToShip password.', '50', '11', now())");
		}

		// Shipper address
		if (!defined('SHIPPING_WAY2SHIP_ORIGIN_ADDRESS')) {
			tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('*Origin address line 1', 'SHIPPING_WAY2SHIP_ORIGIN_ADDRESS', '', 'Address you are shipping from (line 1).', '50', '20', now())");
		}
		if (!defined('SHIPPING_WAY2SHIP_ORIGIN_ADDRESS2')) {
			tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('*Origin address line 2', 'SHIPPING_WAY2SHIP_ORIGIN_ADDRESS2', '', 'Address you are shipping from (line 2).', '50', '21', now())");
		}
		if (!defined('SHIPPING_WAY2SHIP_ORIGIN_CITY')) {
			tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('*Origin city', 'SHIPPING_WAY2SHIP_ORIGIN_CITY', '', 'City you are shipping from.', '50', '22', now())");
		}
		
		if (!defined('SHIPPING_WAY2SHIP_ORIGIN_STATE')) {
			$zone_query = tep_db_query("select zone_code from " . TABLE_ZONES . " where zone_id = '" . (int)STORE_ZONE . "'");
			$zone = tep_db_fetch_array($zone_query);
      		
			tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('*Origin state', 'SHIPPING_WAY2SHIP_ORIGIN_STATE', '" . $zone['zone_code'] . "', 'Enter two letter state/province you are shipping from.', '50', '23', now())");
		}

		if (!defined('SHIPPING_WAY2SHIP_ORIGIN_ZIP')) {
			tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('*Origin zip/postal code', 'SHIPPING_WAY2SHIP_ORIGIN_ZIP', '" . SHIPPING_ORIGIN_ZIP. "', 'Enter ZIP/Postal code are shipping from.', '50', '24', now())");
		}
				
		if (!defined('SHIPPING_WAY2SHIP_ORIGIN_COUNTRY')) {
			tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, use_function, date_added) values ('*Origin country', 'SHIPPING_WAY2SHIP_ORIGIN_COUNTRY', '" . STORE_COUNTRY . "', 'Select the country you are shipping from.', '50', '25', 'tep_cfg_pull_down_country_list(', 'tep_get_country_name', now())");
		}		
		
		// Shipping contact
		if (!defined('SHIPPING_WAY2SHIP_SHIPPING_CONTACT')) {
			tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('*Shipping contact name', 'SHIPPING_WAY2SHIP_SHIPPING_CONTACT', '" . STORE_OWNER . "', 'Name of the person/department responsible for shipping.', '50', '30', now())");
		}
		if (!defined('SHIPPING_WAY2SHIP_SHIPPING_CONTACT_PHONE')) {
			tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('*Shipping contact phone number', 'SHIPPING_WAY2SHIP_SHIPPING_CONTACT_PHONE', '', 'Phone number of the person/department responsible for shipping.', '50', '31', now())");
		}
		if (!defined('SHIPPING_WAY2SHIP_SHIPPING_CONTACT_EMAIL')) {
			tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('*Shipping contact email address', 'SHIPPING_WAY2SHIP_SHIPPING_CONTACT_EMAIL', '" . STORE_OWNER_EMAIL_ADDRESS . "', 'Email address of the person/department responsible for shipping.', '50', '32', now())");
		}

		// Options
		if (!defined('SHIPPING_WAY2SHIP_ORDER_STATUS_TOSHIP')) {
			tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, use_function, date_added) values ('Ship orders with status', 'SHIPPING_WAY2SHIP_ORDER_STATUS_TOSHIP', '2', 'Generate shipping labels for orders with status', '50', '40', 'tep_cfg_pull_down_order_statuses(', 'tep_get_order_status_name', now())");
		}
		if (!defined('SHIPPING_WAY2SHIP_ORDER_STATUS_TOUPDATE')) {
			tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, use_function, date_added) values ('Update shipped orders to Status', 'SHIPPING_WAY2SHIP_ORDER_STATUS_TOUPDATE', '3', 'After generating shipping labels updates orders to status', '50', '41', 'tep_cfg_pull_down_order_statuses(', 'tep_get_order_status_name', now())");
		}
		if (!defined('SHIPPING_WAY2SHIP_NOTIFY_CUSTOMER_ON_SHIPPING')) {
			tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Send email shipment confirmation', 'SHIPPING_WAY2SHIP_NOTIFY_CUSTOMER_ON_SHIPPING', 'True', 'Do you want customers to recieve email notifications on shipment?', '50', '42', 'tep_cfg_select_option(array(\'True\', \'False\'), ', now())");		
		}					
		
		
		// Weight
		if (!defined('SHIPPING_WAY2SHIP_WEIGHT_UNITS')) {
			tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('*Units of weight', 'SHIPPING_WAY2SHIP_WEIGHT_UNITS', 'lbs', 'Units of weight in product properties to use in quotes.', '50', '50', 'tep_cfg_select_option(array(\'lbs\', \'kg\'), ', now())");
		}

		// Dimensions
		if (!defined('SHIPPING_WAY2SHIP_DIM_UNITS')) {
			tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Optional units for dimention fields', 'SHIPPING_WAY2SHIP_DIM_UNITS', 'inch', 'Optional units for values in dimentional fields in the products table.', '50', '60', 'tep_cfg_select_option(array(\'inch\', \'cm\'), ', now())");
		}
		
		if (!defined('SHIPPING_WAY2SHIP_DIM_LENGTH_FIELD')) {
			tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Optional name of length field', 'SHIPPING_WAY2SHIP_DIM_LENGTH_FIELD', '', 'Optional name of length field in the products table. Leave empty if not used.', '50', '61', now())");
		}
		if (!defined('SHIPPING_WAY2SHIP_DIM_WIDTH_FIELD')) {
			tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Optional name of width field', 'SHIPPING_WAY2SHIP_DIM_WIDTH_FIELD', '', 'Optional name of width field in the products table. Leave empty if not used.', '50', '62', now())");
		}

		if (!defined('SHIPPING_WAY2SHIP_DIM_HEIGHT_FIELD')) {
			tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Optional name of height field', 'SHIPPING_WAY2SHIP_DIM_HEIGHT_FIELD', '', 'Optional name of height field in the products table. Leave empty if not used.', '50', '63', now())");
		}
		
		// Taxes and handling
		if (!defined('SHIPPING_WAY2SHIP_TAX_CLASS')) {
			tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, use_function, set_function, date_added) values ('Tax Class', 'SHIPPING_WAY2SHIP_TAX_CLASS', '0', 'Use the following tax class on the shipping fee.', '50', '80', 'tep_get_tax_class_title', 'tep_cfg_pull_down_tax_classes(', now())");
		}
		if (!defined('SHIPPING_WAY2SHIP_HANDLING_FEE')) {
			tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Handling fee', 'SHIPPING_WAY2SHIP_HANDLING_FEE', '0', 'Handling fee to add to shipping quotes.', '50', '81', now())");
		}
				
	}
	 
}

?>